package com.yc.moive.http;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class IBaseHttp extends HttpServlet{
	private static final long serialVersionUID = 7669703948329457212L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//
		String url= request.getRequestURI(); //获取请求地址 /vote/user/login
		String path = url.substring(url.lastIndexOf("/")+ 1);
		
		Method[] methods = this.getClass().getDeclaredMethods();
		
		for(Method method : methods) {
			if(path.equals(method.getName())) {//说明就是受调用这个方法执行

					try {
						method.invoke(this,request, response);
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						e.printStackTrace();
					}
					
						return;
				
			}
		}
		this.error(request,response);
	}

	private void error(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out =response.getWriter();
		//http ://127.0.0.1:8080/vote
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
		out.print("<script>alert('该请求不支持。。。);location.href='"+basePath + "index.html';<script>");
		out.flush();
		out.close();
	}
	
	protected void send(HttpServletResponse response,int code ,Object data) throws IOException {
		response.setContentType("text/plain;charset=utf-8");
		PrintWriter out =response.getWriter();
		Gson gson = new GsonBuilder().serializeNulls().create();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("code", code);
		map.put("data", data);
		out.print(gson.toJson(map));
		out.flush();
		out.close();
	}
	
	protected void send(HttpServletResponse response,Object data) throws IOException {
		response.setContentType("text/plain;charset=utf-8");
		PrintWriter out =response.getWriter();
		Gson gson = new GsonBuilder().serializeNulls().create();
		out.print(gson.toJson(data));
		out.flush();
		out.close();
		
	}

}
